<template>
  <div class="add-qrcode-link__section">
    <a class="access_url" target="_blank" :href="allAccessUrl">{{allAccessUrl}}</a>
    <el-form ref="outLinkForm" :rules="rules" label-width="78px" :model="form" label-position="left">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="指定技能组:"  prop="toPeer"  label-width="90px">
            <el-select class="input_box" v-model="form.toPeer" filterable placeholder="请选择">
              <el-option
                v-for="item in peerOptions"
                :key="item.Exten"
                :label="item.DisplayName"
                :value="item.Exten">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="指定座席:"  prop="agent"  label-width="90px">
            <el-select class="input_box"
                     v-model="form.agent"
                     filterable
                     size="mini"
                     placeholder="请选择">
            <el-option
              v-for="item in agentOptions"
              :label="item.label"
              :value="item.exten"
              :key="item.exten">
            </el-option></el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="语言:"  prop="language"  label-width="42px">
            <el-select class="input_box"
                     v-model="form.language"
                     filterable
                     size="mini"
                     placeholder="请选择">
            <el-option
              v-for="item in languageOptions"
              :label="item.label"
              :value="item.value"
              :key="item.value">
            </el-option></el-select>
            <el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">
                <span class="tooltip_text">将根据您设置的语言生成对应语言的访客端页面</span>
              </div>
              <span class="iconfont icon-tixingweizhi"></span>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="会话来源名称:" prop="source" label-width="90px">
            <el-input class="input_box" v-model.trim="form.source"></el-input>
            <!-- <el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">
                <span class="tooltip_text">座席可以在聊天界面看到该会话的来源</span>
                <img class="tooltip_img" src="../../../../.././../assets/img/config/chat_from.png" alt="">
              </div>
              <span class="iconfont icon-tixingweizhi"></span>
            </el-tooltip> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="会话来源URL:"  prop="url" label-width="90px">
            <el-input class="input_box" v-model.trim="form.url"></el-input>
            <!-- <el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">
                <span class="tooltip_text">{{$t('configLazyLoad.channel.codeTip2')}}</span>
                <img class="tooltip_img" src="../../../../.././../assets/img/config/URL.png" alt="">
              </div>
              <span class="iconfont icon-tixingweizhi"></span>
            </el-tooltip> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="" prop="isQRcode" label-width="0px">
            <el-checkbox v-model="form.isQRcode">{{$t('configLazyLoad.channel.geneCode')}}</el-checkbox>
            <el-tooltip class="example_tip" effect="dark" placement="bottom">
              <img slot="content" src="./img/webLinkExample.png" alt="" style="max-width: 30em"/>
              <span class="example">{{$t('configLazyLoad.channel.viewExample')}}</span>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :offset="18" :span="6" :class="{'item-col__right':layout !== 'inline'}">
          <el-form-item label-width="20px">
            <div class="btn-wapper">
              <el-button class="primary_btn" @click.stop="cannel('outLinkForm')">{{$t('public.cancel')}}</el-button>
              <el-button type="primary" :disabled="!loading" class="primary_btn" @click.stop="onSubmit('outLinkForm')">{{$t('public.save')}}</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <qrcode-image
      ref="qrcode"
      :layout="layout"
      class="qrcode-image"
      v-show="form.isQRcode"
      :isQRcode="form.isQRcode"
      :initLogo="form.logo"
      @logo-upload-outsize="handleOutSize"
      @logo-upload-loading="handleloading"
      @logo-upload-success="setLogo"
      :allAccessUrl="allAccessUrlForQrcode"/>
  </div>
</template>

<script>
  import QrcodeImage from './QrcodeImage'
  import {deepClone} from '@utils/m7Utils'
  import Pagination from '@/components/public-modules/card/Pagination'
  export default {
    name: 'OutWebLinkQRCodeForm',
    props: {
      layout: {
        type: String,
        default: 'inline'
      },
      accessUrl: String,
      initForm: {
        type: Object,
        default: () => {
          return {
            _id: '',
            source: '',
            url: '',
            logo: {
              name: '',
              url: ''
            },
            updateTime: '',
            isQRcode: false
          }
        }
      }
    },
    data () {
      const rexg = /%|#|&|\+|\/|\?|=/g
      var validateSource = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('configLazyLoad.channel.inputSourceName')))
        } else if (rexg.exec(value)) {
          callback(new Error(this.$t('configLazyLoad.channel.dockingError13')))
        } else {
          callback()
        }
      }
      const urlRexg = /%|#|&|\+|\?|=/g
      var validateUrl = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('configLazyLoad.channel.dockingError14')))
        } else if (urlRexg.exec(value)) {
          callback(new Error(this.$t('configLazyLoad.channel.dockingError15')))
        } else {
          callback()
        }
      }
      return {
        loading: true,
        peerOptions: [{DisplayName: this.$t('public.pleasePick1'), Exten: '', _id: ''}],
        agentOptions: [{label: this.$t('public.pleasePick1'), exten: '', _id: ''}],
        languageOptions: [{label: '中文', value: 'ZHCN'}, {label: '英文', value: 'EN'}],
        boolNum: 1, // 点击座席得时候开始渲染计数秒
        form: {
          _id: '',
          source: '',
          url: '',
          logo: {
            name: '',
            url: ''
          },
          language: 'ZHCN',
          toPeer: '',
          agent: '',
          updateTime: '',
          isQRcode: false
        },
        rules: {
          source: [
            { validator: validateSource, trigger: 'blur' }
          ],
          url: [
            { validator: validateUrl, trigger: 'blur' }
          ]
        }
      }
    },
    watch: {
      initForm (n, o) {
        this.form = deepClone(n)
        if (!this.form.toPeer) {
          this.form.toPeer = ''
        }
        if (!this.form.agent) {
          this.form.agent = ''
        }
      }
    },
    methods: {
      restForm () {
        this.$refs.qrcode.restFileList()
        this.$refs.outLinkForm.resetFields()
      },
      handleOutSize () {
        this.loading = true
      },
      handleloading () {
        this.loading = false
      },
      setLogo () {
        this.loading = true
        this.$message.success(this.$t('configLazyLoad.channel.codeSucc'))
      },
      cannel (formName) {
        this.$refs[formName].resetFields()
        this.$refs.qrcode.restFileList()
        this.$emit('cancel')
      },
      // 点击座席下拉组件开始渲染座席组件(避免首次加载较慢)
      isRenderAgentsTwo (bool) {
        if ((this.boolNum < 2) && bool) {
          this.agentOptions1 = this.agentOptions
          this.boolNum += 1
        }
      },
      onSubmit (formName) {
        let that = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let form = deepClone(that.form) || {}
            let isQr = form.isQRcode
            let imageUrl = isQr ? that.$refs.qrcode.downQRcode() : ''
            form.imageUrl = imageUrl
            form.logo = {}
            try {
              let http = /^http:\/\/.*/i.test(form.url);
              let https = /^https:\/\/.*/i.test(form.url);
              if (!http && !https) {
                form.url = 'http://' + form.url;
              }
            }
            catch {
              this.$message.error(this.$t('webchat.urlError'))
            }
            if (that.$refs.qrcode.fileList && that.$refs.qrcode.fileList.length > 0) {
              form.logo = that.$refs.qrcode.uploadFile
            }
            that.$refs.qrcode.loading = 0
            that.$emit('submit-form', form)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    computed: {
      _id () {
        return this.initForm._id || ''
      },
      allAccessUrl () {
        let strNew = ``
        if (this.form.language) {
          strNew += `&language=${this.form.language}`
        }
        if (this.form.agent && this.form.toPeer) {
          strNew += `&otherParams={"agent":"${this.form.agent}","peerId":"${this.form.toPeer}"}`
        } else if (this.form.agent) {
          strNew += `&otherParams={"agent":"${this.form.agent}"}`
        } else if (this.form.toPeer) {
          strNew += `&otherParams={"peerId":"${this.form.toPeer}"}`
        } 
        return `${this.accessUrl}=${this.form.url}&urlTitle=${this.form.source}` + strNew
      },
      allAccessUrlForQrcode () {
        let strNew = ``
        if (this.form.language) {
          strNew += `&language=${this.form.language}`
        }
        if (this.form.agent && this.form.toPeer) {
          strNew += `&otherParams={"agent":"${this.form.agent}","peerId":"${this.form.toPeer}"}`
        } else if (this.form.agent) {
          strNew += `&otherParams={"agent":"${this.form.agent}"}`
        } else if (this.form.toPeer) {
          strNew += `&otherParams={"peerId":"${this.form.toPeer}"}`
        } 
        return `${this.accessUrl}=${this.form.url}&urlTitle=${encodeURIComponent(this.form.source)}` + strNew
      }
    },
    components: {
      QrcodeImage,
      Pagination
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
        let mailQueues = deepClone(this.$getCache('mailQueues'))
        if (!mailQueues || mailQueues.length === 0) {
          mailQueues = []
        }
        mailQueues.unshift({DisplayName: this.$t('public.pleasePick1'), Exten: '', _id: ''})
        this.peerOptions = deepClone(mailQueues) || [{DisplayName: this.$t('public.pleasePick1'), Exten: '', _id: ''}]
      })
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        agents.map(agent => {
          this.agentOptions.push({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, exten: agent.exten})
        })
      })
      let _id = this.initForm._id || ''
      if (!_id) return
      this.form = deepClone(this.initForm)
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../../assets/common.styl"
  .add-qrcode-link__section
    border-top 1px solid $c-im-offline
    padding 16px 4px
  .el-form
    margin-top 12px
    position relative
  .qrcode-image
    margin-top 18px
    display flex
    justify-content center
    align-items center
  .item-col__right
    .el-form-item
      display flex
      float right
  .btn-wapper
    min-width 192px
  .icon-tixingweizhi
    display inline-block
    width 16px
    height 16px
    border 1px solid #459ae9
    border-radius 50%
    font-size 10px
    color #459ae9
    text-align center
    line-height 16px
    margin-left 6px
    position absolute
    top 10px
  .input_box
    width calc(100% - 20px)
  .tooltip_text
    display block
  .tooltip_img
    display block
    margin 0 auto
    height 60px
  .access_url
    word-break break-all
    line-height 20px
  .example_tip
    font-size 12px
    margin-left 20px
    color #459AE9
</style>
